
var toServerIndexUrl = rootPath + "s/sys/server/index.cgi";
var toEditServerPageUrl = rootPath + "s/sys/server/edit.cgi";//增加或修改页面

var pageListUrl = rootPath + "s/sys/server/pagelist";//分页显示
var saveServerUrl = rootPath + "s/sys/server/save";//保存
var removeServerUrl = rootPath + "s/sys/server/del";//删除
var detailServerUrl = rootPath + "s/sys/server/detail";//获取详情

var synupdateSysmsgUrl = rootPath + "s/sys/msg/synupdate";//同步系统消息到服务器

function queryList(){
	var results;
    $("#datagrid").datagrid({
//        url : pageListUrl,
        pagination:true,//分页控件
        width : 'auto',// 面板宽度，自动列宽 
        height : 'auto',// 面板高度，自动列高 
        nowrap : false,// :当true时，显示数据在同一行上。默认true。
        checkOnSelect: true,
        rownumbers: true,
        selectOnCheck: true,
        singleSelect:false,
        autoRowHeight:true,
        fitColumns: true,
        pageNo :0,
        pageSize :10,
        queryParams : getQueryParam(),
        loadFilter : function (data) {
            if(data.opStatus == "0"){
            	$("#pageNo").val(data.data.pageNo);
            	$("#pageSize").val(data.data.pageSize);
            	results = data.data.results;
            	var rs ={
            		"rows":	data.data.results,
            		"total":data.data.totalRecord
            	};
                return rs;
                
            }
        },
        columns : [ [  {
            field:'_',
            checkbox:true,
            width:'5%'
        },{
            field : 'serverName',
            title : '服务器名称',
            width : '10%',
            align : 'center',
            sortable : true
        }, {
            field : 'contextPath',
            title : '服务器根路径',
            width : '20%',
            align : 'center',
            sortable : true
        }, {
            field : 'areaCode',
            title : '服务器地区编码',
            width : '5%',
            align : 'center',
            sortable : true
        },  {
            field : 'mqttHostIp',
            title : 'MQTT_IP',
            align : 'center',
            width : '15%',
            sortable : true
        }, {
            field : 'mqttTcpHostPort',
            title : 'MQTT_TCP_PORT',
            align : 'center',
            width : '10%',
            sortable : true
            
        }, {
            field : 'mqttSocketHostPort',
            title : 'MQTT_SOCKET_PORT',
            width : '10%',
            align : 'center',
            sortable : true,
        }, 
        {
        	field : 'done',
            title : '服务器状态',
            width :'10%',
            align : 'center',
            formatter: function(value,row){
            		var result = "";
            		if(value == "0"){//正常的情况
            			result += '<font style="color:green">正常</font>';
            		}else {
            			result += '<font style="color:red">异常</font>';
            		}
            		
            		return result;
            }
        	
        },
        {
            field : 'serverId',
            title : '操作',
            width :'15%',
            align : 'center',
            formatter: function(value,row){
            		var result = "";
            		result += '<button class="btn btn-default btn-xs" type="button" onclick="toEditServerPage(\''+value+'\')"><i class="glyphicon glyphicon-pencil"></i> 修改 </button>';
            		return result;
            },
            sortable : true
        }] ],
        onDblClickRow : function(index,row){
        }
    });
}

//获取表单参数
function getQueryParam() {
	var pageNo;
	var pageNoStr = $("#pageNo").val();
	if(pageNoStr && pageNoStr != ""){
		pageNo = parseInt(pageNoStr);
	}
	var pageSize;
	var pageSizeStr = $("#pageSize").val();
	if(pageSizeStr && pageSizeStr != ""){
		pageSizeStr = parseInt(pageSizeStr);
	}
	
	var param = {
    		pageNo : pageNo,
    		pageSize : pageSize,
    		"AreaSeverEntity.serverName" : $("#serverName").val(),
            "AreaSeverEntity.contextPath" : $("#contextPath").val(),
            "AreaSeverEntity.areaCode" : $("#areaCode").val(),
    };
    return param;
	
}

//刷新
function refreshGrid(){
	 $("#datagrid").datagrid("reload",getQueryParam());
}

//批量删除服务器的方法
function removeServer(serverIds) {
    var idsStr = serverIds.join(",");
    $.ajax({
        url : removeServerUrl,
        type : 'post',
        data :{ids :idsStr},
        success : function (res) {
            if(res.opStatus == "0"){
                showTip(res.msgDesc,1000,function () {
                	refreshGrid();
                });
            }else {
                showMsg(res.msgDesc);
            }
        }
    })
};

//保存服务器
function saveServer() {
	
	var valiMsg = validate();//验证表单信息
    if(valiMsg != ""){
        showMsg(valiMsg);
        return;
    }
	var param = {
		
		"AreaSeverEntity.serverId" : $("#edit_serverId").val(),
		"AreaSeverEntity.serverName" : $("#edit_serverName").val(),
		"AreaSeverEntity.contextPath" : $("#edit_contextPath").val(),
		"AreaSeverEntity.areaCode" : $("#edit_areaCode").val(),
		"AreaSeverEntity.proxyId" : $("#edit_proxyId").val(),
		"AreaSeverEntity.proxySecret" : $("#edit_proxySecret").val(),
		"AreaSeverEntity.mqttHostIp" : $("#edit_mqttHostIp").val(),
		"AreaSeverEntity.mqttTcpHostPort" : $("#edit_mqttTcpHostPort").val(),
		"AreaSeverEntity.mqttSocketHostPort" : $("#edit_mqttSocketHostPort").val(),
		"AreaSeverEntity.mqttAccount" : $("#edit_mqttAccount").val(),
		"AreaSeverEntity.mqttPwd" : $("#edit_mqttPwd").val(),
		"AreaSeverEntity.insuranceSendEmail" : $("#edit_insuranceSendEmail").val(),
		"AreaSeverEntity.insuranceCcEmail" : 	$("#edit_insuranceCcEmail").val(),
		"AreaSeverEntity.needIsurEmail" : 	$("input[name='edit_needIsurEmail']:checked").val()	
	}
	$.ajax({
        url : saveServerUrl,
        type : 'post',
        data :param,
        success :function (res) {
        	if(res.opStatus == "0"){
        	 showTip(res.msgDesc,1000,function () {
                 $("#editModal").modal("hide");

                 refreshGrid();
             });
        	}else {
              showMsg(res.msgDesc);
        	}
        }
    });
}

//转到编辑页面（修改或增加）
function toEditServerPage(serverId){
	if(serverId && serverId != ""){
		//修改
		$("#edit-modal").load(toEditServerPageUrl + "?serverId=" + serverId,{_: Math.random()},function () {
			 $.ajax({
		            url : detailServerUrl,
		            type : 'post',
		            data :{'id' : serverId},
		            success :function (res) {
			               if( res.opStatus == "0"){
			            	   
			            	   $("#edit_serverName").val(res.data.serverName);
			            	   $("#edit_contextPath").val(res.data.contextPath);
			            	   $("#edit_areaCode").val(res.data.areaCode);
			            	   $("#edit_proxyId").val(res.data.proxyId);
			            	   $("#edit_proxySecret").val(res.data.proxySecret);
			            	   $("#edit_mqttHostIp").val(res.data.mqttHostIp);
			            	   $("#edit_mqttTcpHostPort").val(res.data.mqttTcpHostPort);
			            	   $("#edit_mqttSocketHostPort").val(res.data.mqttSocketHostPort);
			            	   $("#edit_mqttAccount").val(res.data.mqttAccount);
			            	   $("#edit_mqttPwd").val(res.data.mqttPwd);
			            	   $("#edit_insuranceSendEmail").val(res.data.insuranceSendEmail);
			            	   $("#edit_insuranceCcEmail").val(res.data.insuranceCcEmail);
			            	   $("#edit_needIsurEmail").val(res.data.insuranceCcEmail);
			            	   
			            	   //服务器编码不能修改
			            	   $("#edit_areaCode").attr("readonly","readonly");
			            	   
			               }else {
			            	   showMsg(res.msgDesc);
			               }
			               $('#editModalLabel').html("修改");
			               $('#editModal').modal('show');
			               
		                }
		        });
		    });
	}else {//添加
		$("#edit-modal").load(toEditServerPageUrl,{_: Math.random()},function () {
			 $('#editModal').modal('show');
		});
	}
}

//验证表单信息
function validate(){
	var msg = "";
//	$("#serverEdit input[require='true']").each(function(){
//		var str = $(this).val();
//		if(str == null || str == "" || str.length < 1){
//			msg += $(this).attr("data-message") + "</br>";
//		}
//	});
	//必填项的自定义属性 require 为 true,获取这些 input ,如果所填内容为空，则显示提示信息（data-message属性）
	var inputs = $("#serverEdit input[require='true']");
	var err = checkEmpty(inputs);
	debugger;
	$(err).each(function(){
		msg += $(this).attr("data-message")+"</br>";
	});
	var needIsurEmail = $("input[name='edit_needIsurEmail']:checked").val();//是否发送保险邮件
	if(needIsurEmail == null || needIsurEmail == ""){
    	msg += "请选择是否发送保险邮件"+"</br>";
    }
	var contextPath = $("#edit_contextPath").val();//完整根路径(例如: http://61.157.91.8:12800/cloud_base)
	if(contextPath.length > 32 || !(/^http:\/\//.test(contextPath))){
		//以http://开头
    	msg += "正确根路径(http://IP:port/application_name)"+"</br>";
    }
	var insuranceSendEmail = $("#edit_insuranceSendEmail").val();//购买保险的邮箱
	if(insuranceSendEmail.indexOf('@') <= 0 || insuranceSendEmail.indexOf('@') > 20 || insuranceCcEmail.indexOf('@') <= 0 || insuranceCcEmail.indexOf('@') > 20){
    	msg += "@前长度不大于20"+"</br>";
    }
	
	return msg;
}

//同步消息
function synupdateSysmsg(serverIds) {
	var idsStr = serverIds.join(",");
	$.ajax({
		url : synupdateSysmsgUrl,
		type : 'post',
		data :{ids :idsStr},
		success : function (res) {
			if(res.opStatus == "0"){
				showMsg("操作成功！<br>同步情况如下：<br>"+JSON.stringify(res.data));
            }else {
                showMsg(res.msgDesc);
            }
		}
	})
};

$(document).ready(function () {
	queryList();// 加载服务器分页数据
	
	$("#search_button").on("click",function () {
		refreshGrid();
    });
	
	$("#remove_button").on("click",function () {
    	var rows = $("#datagrid").datagrid("getChecked");
        if(rows.length > 0){
            showConfirm("是否确认删除？",function () {
                var serverIds = [];
                for(var i in rows ){
                	serverIds.push(rows[i].serverId);
                }
                removeServer(serverIds);
            });
        }else {
            showMsg("请选择要删除的服务器！");
        }
		
	});
	
	$("#add_button").on("click",function(){
		toEditServerPage("");
	});
	
	$("#synupdate_button").on("click",function(){
		
		var rows = $("#datagrid").datagrid("getChecked");
	    if(rows.length > 0){
	        showConfirm("是否确认同步？",function () {
	            var serverIds = [];
	            for(var i in rows ){
	            	serverIds.push(rows[i].serverId);
	            }
	            synupdateSysmsg(serverIds);
	        });
	    }else {
	        showMsg("请选择要同步的服务器！");
	    }
		
	});
	
	var rows = $("#datagrid").datagrid("getPager");
	 $("#datagrid").datagrid({
		url : pageListUrl,
        onBeforeLoad:function(param){
            param.pageSize = param.rows;
            param.pageNo = param.page;
            param.rows = null;
            param.page = null;
        }
    }); 
	
});

